<?php


namespace app\app\controller;

use app\admin\model\AdminUser;
use app\common\controller\Homebase;
use EasyWeChat\Factory;
use think\Controller;
use think\Db;
use think\Facade;
use think\facade\Config;
use think\facade\Session;
use util\Random;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class index extends Controller
{

    public static function sendAliyunSms($phone, $signName, $templateCode, $templateParam)
    {
        // 初始化客户端
        AlibabaCloud::accessKeyClient(
            'LTAI5tQ79ZzCBiyFGKZiAFdv',      // 替换为你的AccessKey ID
            'B9k5lUrPhX68IFaBUqSrt70r08HEMz'   // 替换为AccessKey Secret
        )->regionId('cn-hangzhou')     // 默认杭州区域
        ->asDefaultClient();

        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'PhoneNumbers' => $phone,
                        'SignName' => $signName,
                        'TemplateCode' => $templateCode,
                        'TemplateParam' => json_encode($templateParam),
                    ],
                ])
                ->request();
            return $result->toArray();
        } catch (ClientException $e) {
            return ['error' => $e->getErrorMessage()];
        } catch (ServerException $e) {
            return ['error' => $e->getErrorMessage()];
        }
    }

    public function template2()
    {
        $data = $this->sendAliyunSms('16653193224',          // 手机号（注意去掉+号）
            '山东省鉴证技术咨询',                 // 短信签名
            'SMS_482590012',         // 模板CODE
            ['code' => rand(1000, 9999)]);// 模板参数);
        msg(0, "获取成功", $data);
    }

    //    ------------------------------工具方法--------------------------------------------

    /**
     * 请求
     * @param $url
     * @param null $data
     * @return bool|string
     */
    private function http_request($url, $data = null)
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, TRUE);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json'
            ));
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
        exit();

    }


    //    ------------------------------基本信息--------------------------------------------

    /**
     * 上传图片
     */
    // todo 转换成webp 看图片压缩
    public function upload_img()
    {
        $files = $this->request->file('file');//获取图片
        $info = $files->move(ROOT_PATH . 'public' . '/' . 'uploads');

        if ($info) {

            $logo = '/' . 'uploads' . '/' . $info->getSaveName();

            $datas = $info->getInfo();

            $img['path'] = $logo;

            $img['mime'] = $datas['type'];

            $img['name'] = $datas['name'];

            $img['size'] = $datas['size'];

            $img['sha1'] = $info->hash('sha1');

            $img['md5'] = $info->hash('md5');

            $img['driver'] = 'local';

            $img['create_time'] = time();

            $img['update_time'] = time();

            $img['status'] = 1;

            $img['ext'] = $info->getExtension();

            $id = Db::name('attachment')->insertGetId($img);
            //todo 关闭oss
//            if (config('is_oss') == 1) {
//                upload_local_file($id);
//            }
            $d = db('attachment')->where('id', $id)->find();
            if ($d['type'] == 1) {
                $d['path'] = conf("wechat", "url") . str_replace('\\', '/', $d['path']);
            } else {
                $d['path'] = conf("wechat", "url") . $d['path'];
            }
            msg(0, "获取成功", $d);

        } else {
            echo $files->getError();
        }
        //msg(0, "成功", $url);
    }

    //    ------------------------------天津翔业--------------------------------------------
    //获取验证码
    public function getVerify()
    {

    }
    //注册用户


    //登录
    public function login2()
    {
        $data = $this->request->param();
        $username = trim($data['account']);
        $password = trim($data['password']);
        $admin = AdminUser::get(['username' => $username]);
        if (!$admin) {
            msg(-1, '用户名不正确', '', '');
        }
        if ($admin['status'] !== 1) {
            msg(-1, '管理员已经被禁止登录', '', '');
        }
        if (Config::get('login_failure_retry') && $admin->login_failure >= 10 && time() - $admin->getData('update_time') < 86400) {
            msg(-1, '请于1天后再尝试登录', '', '');
        }
        if ($admin->password != encrypt_password($password, $admin->encrypt)) {
            msg(-1, '密码不正确', '', '');
        }
        $admin->token2 = md5(time() . $password);
        $admin->save();
        msg(0, '登陆成功', $admin, '');
    }

    //发送消息
    public function senMsg()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            sendMsg(1, '物价评估', '您的物价评估已完成，请查看', 100);
            Db::commit();
            msg(0, '修改成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    public function zhuanjiaCate()
    {
        $data = $this->request->param();
        $cate_list = Db::name('content_cate')->where([
            'is_del' => 0,
        ])->dec('sort desc')->select();
        msg(0, '修改成功', $cate_list);
    }

    //发送验证码
    public function sendVerifyCode()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            if (!$data['phone']) {
                msg(-1, '请填写手机号', '');
            }
            $code = sendVerifyCode($data['phone']);
            Db::commit();
            msg(0, '发送成功', $code);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //注册
    public function register()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            if (!$data['phone']) {
                msg(-1, '请填写手机号', '');
            }
            if (!$data['verifyCode']) {
                msg(-2, '验证码', '');
            }
            if (!checkCode($data['phone'], $data['verifyCode'])) {
                msg(-1, '验证码错误', '');
            }
            $member = Db::name('member')->where([
                'mobile' => $data['phone']
            ])->find();
            if ($member) {
                msg(-1, '手机号已注册', '');
            }
            $insert_data = array(
                'nickname' => '用户' . rand(10000, 99999),
                'mobile' => $data['phone'],
                'create_time' => time(),
                'status' => 0,
                'query_num' => 0,
                'reg_ip' => $this->request->ip()
            );
            $id = Db::name('member')->insertGetId($insert_data);
            Db::commit();
            msg(0, '创建成功', $id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //登录
    public function login()
    {
        $data = $this->request->param();
        $phone = trim($data['phone']);
        $password = trim($data['password']);
        $member = Db::name('member')->where([
            'mobile' => $phone,
            'password' => md5($password)
        ])->find();
        if (!$member) {
            msg(-1, '用户或密码错误', '', '');
        }
        if ($member['status'] == 0) {
            msg(-1, '账号未开通，请联系管理员', '', '');
        }
        if ($member['token']) {
            $token = $member['token'];
        } else {
            $token = generateToken($member['mobile']);
        }
        $update = array(
            'id' => $member['id'],
            'access_token' => $token
        );
        Db::name('member')->update($update);
        $member['access_token'] = $token;
        msg(0, '发送成功', $member);
    }

    //获取首页栏目
    public function getIndexColumn()
    {
        $data = Db::name('column')
            ->where(['is_del' => 0, 'status' => 1])
            ->order('sort desc')->select();
        msg(0, '发送成功', $data);
    }

    //发送找回密码验证码
    public function sendVerifyCode2()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            if (!$data['phone']) {
                msg(-1, '请填写手机号', '');
            }
            $code = sendVerifyCode($data['phone']);
            Db::commit();
            msg(0, '发送成功', $code);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //发送找回密码验证码
    public function sendVerifyCode3()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            if (!$data['phone']) {
                msg(-1, '请填写手机号', '');
            }
            $code = sendVerifyCode($data['phone']);
            Db::commit();
            msg(0, '发送成功', $code);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //忘记密码
    public function forgetPassword()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            if ($data['password1'] != $data['password2']) {
                msg(-1, '两次密码不正确', '');
            }
            if (!checkCode($data['phone'], $data['verifyCode'])) {
                msg(-1, '验证码错误', '');
            }
            Db::name('member')->where('mobile', '=', $data['phone'])->update([
                'password' => md5($data['password1']),
            ]);
            Db::commit();
            msg(0, '修改完成', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    /**
     * 获取各项配置
     */
    public function getConfigAdmin()
    {
        $data = $this->request->param();
        if ($data['set_name'] && isset($data['set_name'])) {
            msg(0, '查询完成', config('site.' . $data['set_name']));
        }
        msg(-1, '请输入查询内容', '');
    }

    //各项配置
    public function getConfigAdmin2()
    {
        $return['logo'] = config('site.logo');
        $return['web_logo2'] = config('site.web_logo2');
        $return['web_index_title'] = config('site.web_index_title');
        $return['phone'] = config('site.phone');
        $return['contact_email'] = config('site.contact_email');
        $return['address'] = config('site.address');
        $return['weixin'] = config('site.weixin');
        $return['beian'] = config('site.beian');
        $return['beian_url'] = config('site.beian_url');
        $return['copyright'] = config('site.copyright');
        $return['technical_support'] = config('site.technical_support');
        msg(0, '查询完成', $return);
    }

    //获取banner
    public function getBanner()
    {
        $banner = Db::name('banner')->where([
            'status' => 1,
            'is_del' => 0
        ])->find();
        msg(0, '查询完成', $banner);
    }

    //获取汇编目录
    public function getCompilation()
    {
        $data = $this->request->param();
        $_list = Db::name('content')
            ->where([
                ['is_del', '=', 0],
                ['pid', '=', 0],
                ['status', '=', 1]
            ])
            ->order('sort desc')
            ->select();
        foreach ($_list as $k => $v) {
            $_list[$k]['is_able']=0;
            $nth = Db::name('content')
                ->where([
                    ['is_del', '=', 0],
                    ['pid', '=', $v['id']],
                ])->order('sort desc')
                ->select();
            foreach ($nth as $k2=>$v2){
                $nth[$k2]['is_able']=0;
                $where2=array();
                $where2[] = ['is_del', '=', 0];
                $where2[] = ['status', '=', 1];
                $where2[] = ['content_id', '=', $v2['id']];
                if(isset($data['name'])&&$data['name']){
                    $where2[] = ['name|gbt', 'like', '%'.$data['name'].'%'];
                }
                $msg_list=Db::name('compilation')
                    ->where($where2)
                    ->order('sort desc')
                    ->paginate(1000, false, [
                        'page' => 1
                    ])->each(function ($item) {
                        $item['create_time'] = date('Y-m-d', $item['create_time']);
                        $item['effect_time'] = date('Y-m-d', $item['effect_time']);
                        return $item;
                    });
                if($data['name']&&!$msg_list){
                    unset($nth[$k2]);
                    continue;
                }
                $nth[$k2]['compilation']=$msg_list;
            }
            $_list[$k]['nth'] = $nth;
        }
          msg(0, '查询完成', $_list);
    }
    //获取编码详情
    public function compilationDetail(){
        $data = $this->request->param();
        $compilation=Db::name('compilation')->find($data['id']);
        msg(0, '查询完成', $compilation);
    }

    //获取品牌列表
    public function getBrand()
    {
        $banner = Db::name('brand')->where([
            'status' => 1,
            'is_del' => 0
        ])->order('sort desc')->select();
        msg(0, '查询完成', $banner);
    }




    //todo 估价项目 客户沟通 阿里云短信购买，配置；后台充值功能，配置接口，修改验证码接口，首页banner图，对接口增加数据；上海陪诊 和设计沟通 会员卡使用相关接口
}